package com.android.meige.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;

import com.android.meige.R;
import com.android.meige.app.BaseActivity;
import com.android.meige.cache.search.RecordsDao;
import com.android.meige.model.group.CitySetData;
import com.android.meige.model.group.CitySetDataCallback;
import com.android.meige.utils.ConstantsUrl;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.LoginState;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.view.MyListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/7/20.
 */

public class CitySearch extends BaseActivity {

    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.canel)
    TextView canel;
    @BindView(R.id.listView)
    MyListView listView;
    private CitySearch mcontext;
    private RecordsDao recordsDao;
    private SearchRecordsAdapter recordsAdapter;
    private String record;
    private List<String> tempList;
    private List<String> tempListid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.city_search);
        ButterKnife.bind(this);
        mcontext = CitySearch.this;
        initUI();
        initSearchData();
        recordsAdapter = new SearchRecordsAdapter(this, tempList);
        listView.setAdapter(recordsAdapter);
    }

    private void initSearchData() {
        recordsDao = new RecordsDao(mcontext);
        tempList = new ArrayList<>();
        tempListid = new ArrayList<>();
    }

    private void initUI() {
        // 监听软键盘
        etSearch.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (etSearch.getText().toString().trim().length() > 0) {
                        record = etSearch.getText().toString().trim();
                        initSearch(record);
                    } else {
                        ObjectUtils.toast(mcontext, "输入内容不能为空");
                    }
                }
                return false;
            }
        });

        // 搜索框的文本变化实时监听
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String tempName = etSearch.getText().toString().trim();
                tempList.clear();
                tempListid.clear();
                tempList.addAll(recordsDao.querySimlarCity(tempName));
                tempListid.addAll(recordsDao.querySimlarCityId(tempName));
                recordsAdapter.notifyDataSetChanged();

            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PostCityChoose(tempListid.get(position));
            }
        });


    }

    private void PostCityChoose(String id) {
        String address = ConstantsUrl.domain + ConstantsUrl.CITYSET;
        String getid = LoginState.getInstance().getid(mcontext);
        String getpd = LoginState.getInstance().getpd(mcontext);
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> header = new HashMap<>();
        header.put("UID", getid);
        header.put("UPSW", getpd);
        map.put("id", id);
        HttpUtils.post(address, header, map, new CitySetDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(CitySetData response, int id) {
                if (response == null) {
                    return;
                }
                if (response.getCode() == 0) {
                    CitySetData.DataBean data = response.getData();
                    if (data != null) {
                        String zone = data.getZone();
                        String returncity = data.getCity();
                        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString(ConstantsUrl.USERDATA_ZONE, zone);
                        edit.putString(ConstantsUrl.USERDATA_CITY, returncity);
                        edit.commit();
                        Intent intent = new Intent();
                        intent.setAction(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_LOCATION_CHANGE);
                        mcontext.sendBroadcast(intent);
                        finish();
                    }
                }
            }
        });
    }

    private void initSearch(String record) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
        }
        tempList.clear();
        tempListid.clear();
        tempList.addAll(recordsDao.querySimlarCity(record));
        tempListid.addAll(recordsDao.querySimlarCityId(record));
        recordsAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.canel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.canel:
                onBackPressed();
                break;
        }
    }


    private class SearchRecordsAdapter extends BaseAdapter {

        private List<String> searchRecordsList;
        private LayoutInflater inflater;

        public SearchRecordsAdapter(Context context, List<String> searchRecordsList) {

            this.searchRecordsList = searchRecordsList;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return searchRecordsList.size() == 0 ? 0 : searchRecordsList.size();
        }

        @Override
        public Object getItem(int position) {
            return searchRecordsList.size() == 0 ? null : searchRecordsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            SearchRecordsAdapter.ViewHolder viewHolder;
            if (null == convertView) {
                viewHolder = new SearchRecordsAdapter.ViewHolder();
                convertView = inflater.inflate(R.layout.dialog_message_item, null);
                viewHolder.recordTv = (TextView) convertView.findViewById(R.id.pay_name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (SearchRecordsAdapter.ViewHolder) convertView.getTag();
            }
            String content = searchRecordsList.get(position);
            viewHolder.recordTv.setText(content);

            return convertView;
        }

        private class ViewHolder {
            TextView recordTv;
        }
    }

}

